package org.wangzs.blog.action.blog;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.wangzs.blog.util.Const;
import org.wangzs.blog.util.Func;

@Controller
public class LoginAction {

	@RequestMapping(value = "/sitemap")
	public String sitemap() {
		return "blog/sitemap";
	}

	@RequestMapping(value = "/login")
	public String login(HttpServletRequest request,
			@CookieValue(value = "username", required = false) String username,
			@CookieValue(value = "password", required = false) String password) {
		if ("e241138".equals(username) && "BBbb138717".equals(password)) {
			return "redirect:/posts";
		} else {
			return "blog/login";
		}
	}

	@RequestMapping(value = "/logout")
	public String logout(HttpServletRequest request,
			HttpServletResponse response) {
		Func.clearCookie(request, response);
		return "redirect:/";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String hashLogin(
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "captcha", required = true) String captcha,
			HttpServletRequest request, HttpServletResponse response) {
		if ("e241138".equals(username)
				&& "BBbb138717".equals(password)
				&& captcha.equalsIgnoreCase((String) request.getSession().getAttribute(
						Const.SESSION_CAPTCHA))) {
			Cookie cookie1 = new Cookie("username", username);
			Cookie cookie2 = new Cookie("password", password);
			response.addCookie(cookie1);
			response.addCookie(cookie2);
			return "redirect:/posts/1";
		} else {
			return "redirect:/login";
		}
	}
}
